<template>
  <div class="goodsindex">
    <!-- 搜索条件 -->
    <div style="display: flex; align-items: center">
      <el-date-picker
        v-model="value1"
        size="small"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
      <el-button
        type="primary"
        size="small"
        @click="select"
        style="margin-left: 10px"
        >搜索</el-button
      >
    </div>
    <div id="main"></div>
    <el-tabs type="border-card" v-model="activeName" @tab-remove="tabRemoveFun">
      <el-tab-pane label="所有产品统计" name="first" :closable="false">
        <div class="divs">
          <el-button
            type="primary"
            size="small"
            @click="exportFun(1)"
            style="margin-bottom: 10px"
            >导出</el-button
          >
          <el-table
            :data="
              indexData.length
                ? indexData.slice(
                    (pageIndex - 1) * pageSize,
                    pageIndex * pageSize
                  )
                : []
            "
            border
            size="mini"
            style="width: 100%"
            ref="dataTable"
            :height="tableMaxHeight"
            @cell-dblclick="celldblclick"
          >
            <el-table-column
              type="index"
              header-align="center"
              align="center"
              label="序"
              width="50"
            >
            </el-table-column>
            <el-table-column
              prop="productName"
              header-align="center"
              align="center"
              label="产品序号"
              width="180"
            >
            </el-table-column>
            <el-table-column
              prop="userCompany"
              header-align="center"
              align="center"
              label="用户名称"
            >
            </el-table-column>
            <el-table-column
              prop="userName"
              header-align="center"
              align="center"
              label="姓名"
            >
            </el-table-column>
            <el-table-column
              prop="userAddress"
              header-align="center"
              align="center"
              label="地址"
            >
            </el-table-column>
            <el-table-column
              prop="problemDesc"
              header-align="center"
              align="center"
              label="现场问题描述"
            >
            </el-table-column>
            <el-table-column
              prop="createTime"
              header-align="center"
              align="center"
              label="创建时间"
            >
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-row :gutter="20" class="goodsindex-list">
            <el-col :span="24" class="goodsindex-page-box">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageIndex"
                :page-sizes="[1, 2, 10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalPage"
              >
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane
        :label="wentiName + '产品统计'"
        name="second"
        v-if="wentiData.length"
        :closable="true"
      >
        <div class="divs">
          <el-button
            type="primary"
            size="small"
            @click="exportFun(2)"
            style="margin-bottom: 10px"
            >导出</el-button
          >
          <el-table
            :data="
              wentiData.slice(
                (pageIndex0 - 1) * pageSize0,
                pageIndex0 * pageSize0
              )
            "
            border
            size="mini"
            style="width: 100%"
            ref="dataTable"
            :height="tableMaxHeight"
            @cell-dblclick="celldblclick"
          >
            <el-table-column
              type="index"
              header-align="center"
              align="center"
              label="序"
              width="50"
            >
            </el-table-column>
            <el-table-column
              prop="productName"
              header-align="center"
              align="center"
              label="产品序号"
              width="180"
            >
            </el-table-column>
            <el-table-column
              prop="userCompany"
              header-align="center"
              align="center"
              label="用户名称"
            >
            </el-table-column>
            <el-table-column
              prop="userName"
              header-align="center"
              align="center"
              label="姓名"
            >
            </el-table-column>
            <el-table-column
              prop="userAddress"
              header-align="center"
              align="center"
              label="地址"
            >
            </el-table-column>
            <el-table-column
              prop="problemDesc"
              header-align="center"
              align="center"
              label="现场问题描述"
            >
            </el-table-column>
            <el-table-column
              prop="createTime"
              header-align="center"
              align="center"
              label="创建时间"
            >
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-row :gutter="20" class="goodsindex-list">
            <el-col :span="24" class="goodsindex-page-box">
              <el-pagination
                background
                @size-change="handleSizeChange0"
                @current-change="handleCurrentChange0"
                :current-page="pageIndex0"
                :page-sizes="[1, 2, 10, 20, 50, 100]"
                :page-size="pageSize0"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalPage0"
              >
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane
        :label="labelname + '单个产品统计'"
        name="three"
        v-if="singleTableData.length"
        :closable="true"
      >
        <div class="divs">
          <el-button
            type="primary"
            size="small"
            @click="exportFun(3)"
            style="margin-bottom: 10px"
            >导出</el-button
          >
          <el-table
            :data="
              singleTableData.slice(
                (pageIndex1 - 1) * pageSize1,
                pageIndex1 * pageSize1
              )
            "
            border
            size="mini"
            style="width: 100%"
            ref="dataTable"
            :height="tableMaxHeight"
          >
            <el-table-column
              type="index"
              header-align="center"
              align="center"
              label="序"
              width="50"
            >
            </el-table-column>
            <el-table-column
              prop="productName"
              header-align="center"
              align="center"
              label="产品序号"
              width="180"
            >
            </el-table-column>
            <el-table-column
              prop="userCompany"
              header-align="center"
              align="center"
              label="用户名称"
            >
            </el-table-column>
            <el-table-column
              prop="userName"
              header-align="center"
              align="center"
              label="姓名"
            >
            </el-table-column>
            <el-table-column
              prop="userAddress"
              header-align="center"
              align="center"
              label="地址"
            >
            </el-table-column>
            <el-table-column
              prop="problemDesc"
              header-align="center"
              align="center"
              label="现场问题描述"
            >
            </el-table-column>
            <el-table-column
              prop="createTime"
              header-align="center"
              align="center"
              label="创建时间"
            >
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-row :gutter="20" class="goodsindex-list">
            <el-col :span="24" class="goodsindex-page-box">
              <el-pagination
                background
                @size-change="handleSizeChange1"
                @current-change="handleCurrentChange1"
                :current-page="pageIndex1"
                :page-sizes="[1, 2, 10, 20, 50, 100]"
                :page-size="pageSize1"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalPage1"
              >
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
export default {
  data() {
    return {
      xData: [],
      yData: [],
      userList: [],
      value1: [],
      indexData: [],
      startTime: "",
      endTime: "",
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      wentiData: [],
      pageIndex0: 1,
      pageSize0: 10,
      totalPage0: 0,
      singleTableData: [],
      pageIndex1: 1,
      pageSize1: 10,
      totalPage1: 0,
      activeName: "first",
      labelname: "",
      wentiName: "",
      faultTypeRootIds: "",
      productId: "",
    };
  },
  mounted() {
    this.startTime = this.getYear();
    this.endTime = this.commonAddMouth();
    this.value1 = [this.startTime, this.endTime];
    this.getList();
  },
  computed: {
    showOrHide() {
      // if(this.isAuth('')==false&&this.isAuth('')==false&&this.isAuth('')==false){
      //     this.isShowOrHide=false;
      // }
      return true;
    },
    tableMaxHeight() {
      return window.innerHeight - 615 + "px";
    },
  },
  methods: {
    commonAddMouth() {
      let dat = new Date();
      //获取年月日，时间
      var year = dat.getFullYear();
      var mon =
        dat.getMonth() + 1 < 10
          ? "0" + (dat.getMonth() + 1)
          : dat.getMonth() + 1;
      var data = dat.getDate() < 10 ? "0" + dat.getDate() : dat.getDate();
      var hour = dat.getHours() < 10 ? "0" + dat.getHours() : dat.getHours();
      var min =
        dat.getMinutes() < 10 ? "0" + dat.getMinutes() : dat.getMinutes();
      var seon =
        dat.getSeconds() < 10 ? "0" + dat.getSeconds() : dat.getSeconds();

      var newDate =
        year + "-" + mon + "-" + data + " " + hour + ":" + min + ":" + seon;

      return newDate;
    },
    getYear(index = 1) {
      let dateTime = new Date(); /* 获取现在的年份 */
      // dateTime.setFullYear(dateTime.getFullYear() + Number(index));
      dateTime.setMonth(dateTime.getMonth() - Number(index));
      // dateTime.setDate(dateTime.getDate() - 1);
      dateTime.setDate(dateTime.getDate());
      var y = dateTime.getFullYear();
      var m = dateTime.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = dateTime.getDate();
      d = d < 10 ? "0" + d : d;
      var h = dateTime.getHours();
      h = h < 10 ? "0" + h : h;
      var min = dateTime.getMinutes();
      min = min < 10 ? "0" + min : min;
      var s = dateTime.getSeconds();
      s = s < 10 ? "0" + s : s;
      let date = y + "-" + m + "-" + d + " " + h + ":" + min + ":" + s;
      console.log(date);
      return date;
    },
    select() {
      this.pageIndex = 1;
      this.getList();
    },
    tabRemoveFun(targetName) {
      if (targetName == "second") {
        this.wentiName = "";
        this.wentiData = [];
      } else {
        this.singleTableData = [];
      }
      this.activeName = "first";
    },
    async getList() {
      await this.Sevice({
        url: "product/chart",
        method: "get",
        params: {
          startTime: this.value1 && this.value1.length ? this.value1[0] : "",
          endTime: this.value1 && this.value1.length ? this.value1[1] : "",
        },
      })
        .then((res) => {
          console.log(res);
          if (res && res.code == 200) {
            // this.totalPage = res.res.list.length;
            this.userList = res.res.list;
            this.xData = res.res.x;
            this.yData = res.res.y;
            let data = [];
            for (let i = 0; i < res.res.list.length; i++) {
              data.unshift(...res.res.list[i]);
            }
            this.indexData = data;
            this.totalPage = data.length;
            this.getEcharts();
          } else {
            this.userList = [];
            this.totalPage = 0;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    celldblclick(row, column, cell, event) {
      // console.log(row, column, cell, event)
      this.labelname = row.productName;
      this.productId = row.productId;
      this.Sevice({
        url: "syn/Feedback/list",
        method: "get",
        params: {
          productName: row.productName,
          // userName:row.userName,
          startTime: this.value1.length ? this.value1[0] : "",
          endTime: this.value1.length ? this.value1[1] : "",
        },
      })
        .then((res) => {
          // console.log(res)
          if (res && res.code == 200) {
            this.singleTableData = res.list;
            this.totalPage1 = this.singleTableData.length;
            this.activeName = "three";
          } else {
            this.singleTableData = [];
            this.totalPage1 = 0;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getEcharts() {
      let myChart;
      if (document.getElementById("main") == null) {
        return;
      }
      this.$echarts.dispose(document.getElementById("main"));
      myChart = this.$echarts.init(document.getElementById("main"));
      var option;

      option = {
        grid: {
          left: "3%",
          right: "3%",
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: this.xData,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: this.yData,
            type: "bar",
            barMaxWidth: 40,
          },
        ],
      };

      option && myChart.setOption(option);
      window.onresize = function () {
        myChart.resize();
      };
      myChart.on("click", (params) => {
        console.log(params);
        this.wentiName = params.name;
        this.wentiData = this.userList[params.dataIndex];
        this.faultTypeRootIds =
          this.userList[params.dataIndex][0].faultTypeRootIds;
        this.totalPage0 = this.userList[params.dataIndex].length;
        this.activeName = "second";
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      //   this.getUserlist();
    },
    handleCurrentChange(val) {
      this.pageIndex = val;
      //   this.getUserlist();
    },

    // 分页
    handleSizeChange0(val) {
      this.pageSize0 = val;
      //   this.getUserlist();
    },
    handleCurrentChange0(val) {
      this.pageIndex0 = val;
      //   this.getUserlist();
    },

    // 分页
    handleSizeChange1(val) {
      this.pageSize1 = val;
      //   this.getUserlist();
    },
    handleCurrentChange1(val) {
      this.pageIndex1 = val;
      //   this.getUserlist();
    },
    exportFun(num) {
      let data = {};
      if (num == 1) {
        data = {
          startTime: this.startTime,
          endTime: this.endTime,
        };
      }
      if (num == 2) {
        data = {
          startTime: this.startTime,
          endTime: this.endTime,
          synFaultTypeId: this.faultTypeRootIds,
        };
      }
      if (num == 3) {
        data = {
          startTime: this.startTime,
          endTime: this.endTime,
          productInfoId: this.productId,
        };
      }
      this.Sevice({
        url: "product/fault-statistics-export",
        method: "post",
        data: JSON.stringify(data),
        headers: { "Content-Type": "application/json" },
        responseType: "blob",
      })
        .then((response) => {
          console.log(response);
          if (response.data.code && response.data.code == 500) {
            this.$message.error(response.data.msg);
          } else {
            let blob = new Blob([response.data], {
              type: "application/vnd.ms-excel",
            });
            const fileName = decodeURI(
              response.headers["content-disposition"].split("=")[1]
            );
            // const fileName = '故障统计-' + this.getYMD() + '.xlsx'
            let objectUrl = URL.createObjectURL(blob); // 创建URL
            const link = document.createElement("a");
            link.href = objectUrl;
            // link.download = '.xlsx'// 自定义文件名
            //这里是获取后台传过来的文件名
            link.setAttribute("download", fileName);
            link.click(); // 下载文件
            URL.revokeObjectURL(objectUrl); // 释放内存
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
<style>
#main {
  width: 100%;
  height: 350px;
  /* box-shadow: 0px 0px 5px #ccc; */
  /* margin-top:5px;
    margin-bottom:5px; */
}

.divs {
  /* box-shadow: 0px 0px 5px #ccc; */
}

.goodsindex {
  width: 100%;
  height: 100%;
  padding: 15px;
  box-sizing: border-box;
}

/* 搜索 */
.goodsindex-queryInfo {
  margin-bottom: 10px;
}

.goodsindex-queryInfo-li {
  width: 100%;
  height: auto;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 列表 */
.goodsindex-list {
  width: 100%;
  height: auto;
  margin-top: 20px;
}

/* 分页 */
.goodsindex-page-box {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: flex-end;
}
</style>
